import scrapy
from scrapy_dangdang_41.items import ScrapyDangdang41Item


class DangSpider(scrapy.Spider):
    name = "dang"
    allowed_domains = ["category.dangdang.com"]
    start_urls = ["https://category.dangdang.com/cp01.54.06.19.00.00.html"]

    # 1.https://category.dangdang.com/cp01.54.06.19.00.00.html
    # 2.https://category.dangdang.com/pg2-cp01.54.06.19.00.00.html
    # 3.https://category.dangdang.com/pg3-cp01.54.06.19.00.00.html
    base_url = 'https://category.dangdang.com/pg'
    page = 1

    def parse(self, response):

        # src = '//ul[@id="component_59"]/li//img/@src'
        # name = '//ul[@id="component_59"]/li//img/@alt'
        # price = '//li/p[@class="price"]/span[1]'

        # 所有seletor对象 都可以再次调用xpath方法
        li_list = response.xpath('//ul[@id="component_59"]/li')

        for li in li_list:
            src = li.xpath('.//img/@data-original').extract_first()
            if not src:
                src = response.xpath('.//img/@src').extract_first()
            name = li.xpath('.//img/@alt').extract_first()
            price = li.xpath('.//p/span[@class="search_now_price"]/text()').extract_first()

            book = ScrapyDangdang41Item(src=src, name=name, price=price)

            # 获取一个book就将book交给pipelines
            yield book

        # 每一页的爬取的业务逻辑全都是一样的， 所以我们只需要将执行的哪个页的请求再次调用parse方法就可以了

        if self.page < 100:
            self.page = self.page + 1
            url = self.base_url + str(self.page) + '-cp01.54.06.19.00.00.html'

            #               怎么去调用parse方法
            #               scrapy.Request就是scrapy的get请求
            # url就是请问求地址
            # callback就是你要执行的哪个函数， 注意不需要加()
            yield scrapy.Request(url=url, callback=self.parse)
